package com.zzw.basic.io.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

public class ClientTest {

	private SocketChannel channel = null;
	private InetSocketAddress address = new InetSocketAddress("localhost", 8080);
	private Selector selector = null;
	private ByteBuffer rcBuffer = ByteBuffer.allocate(1024);
	private ByteBuffer sendBuffer = ByteBuffer.allocate(1024);
	
	public ClientTest() throws IOException{
		channel = SocketChannel.open();
		channel.configureBlocking(false);
		channel.connect(address);
		selector = Selector.open();
		channel.register(selector, SelectionKey.OP_CONNECT);
	}
	
	public void session() throws IOException{
		if(channel.isConnectionPending()){
			channel.finishConnect();
			channel.register(selector, SelectionKey.OP_WRITE);
			System.out.println("已经连接到服务器了,可以控制台登记了");
		}
		Scanner scan = new Scanner(System.in);
		while(scan.hasNext()){
			String name = scan.nextLine();
			if("".equals(name)){
				continue;
			}
			if("finish".equals(name)){
				System.exit(0);
			}
			process(name);
		}
	}

	private void process(String name) {
		boolean waitHelp = true;
		Iterator<SelectionKey> iterator = null;
		Set<SelectionKey> keys = null;
		while(waitHelp){
			try {
				int readys = selector.select();
				if(readys == 0){
					continue;
				}
				keys = selector.selectedKeys();
				iterator = keys.iterator();
				while(iterator.hasNext()){
					SelectionKey key = iterator.next();
					if(key.isValid() && key.isWritable()){
						sendBuffer.clear();
						sendBuffer.put(name.getBytes());
						sendBuffer.flip();
						channel.write(sendBuffer);
						channel.register(selector,SelectionKey.OP_READ);
					}
					else if(key.isValid() && key.isReadable()){
						rcBuffer.clear();
						int len = channel.read(rcBuffer);
						if(len > 0){
							System.out.println("服务端反馈的消息:" + new String(rcBuffer.array()));
							waitHelp = false;
						}
					}
					iterator.remove();
				}
			} catch (Exception e) {
				try {
					((SelectionKey)keys).cancel();
					channel.socket().close();
					channel.close();
					return;
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				
			}
		}
	}
	
	public static void main(String[] args) throws IOException {
		new ClientTest().session();
	}
}
